﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using ESOL.Common.Entity;
using ESOL.Business.Sales;
using ESOL.Business.Inv;
using ESOL.Business.Mst;
using ESOL.Common;

namespace ESOL.WinUI.Inv
{
    public partial class frmMaintainReturnImportOrder : BaseForm.frmBaseDialogyBusinessForm
    {
        #region Vars
        private List<SalesReturnItemEntity> mReturnItems;
        public InvReturnImportOrderEntity selectedReturnImportOrder { get; set; }
        private DataRow mSelectedRow;
        #endregion

        #region Cons
        public frmMaintainReturnImportOrder()
        {
            InitializeComponent();
            if (selectedReturnImportOrder == null)
            {
                selectedReturnImportOrder = new InvReturnImportOrderEntity();
                selectedReturnImportOrder.Id = Guid.NewGuid().ToString();
            }
        }
        public frmMaintainReturnImportOrder(List<SalesReturnItemEntity> mlist)
        {
            InitializeComponent();
            mReturnItems = mlist;
            if (selectedReturnImportOrder == null)
            {
                selectedReturnImportOrder = new InvReturnImportOrderEntity();
                selectedReturnImportOrder.Id = Guid.NewGuid().ToString();
                selectedReturnImportOrder.Status = "IRIO01";
            }
            string returnOrderId=((SalesReturnItemEntity)mlist[0]).SalesReturnOrderId;
            SalesReturnOrderEntity entity=SalesReturnOrderBs.GetSalesReturnOrderById(returnOrderId);
            txtReturnCode.Text = entity.OrderCode;
            txtReturnCode.Tag = entity;
        }

        #endregion

        #region Func
        private void BindComboBox()
        {
            UICommon.UICommonFunctions.BindComboboxByCommonItem(cmbStatus, "IRIO", true);
            UICommon.UICommonFunctions.BindGridComboboxByCommonItem(repositoryItemGridLookUpEdit1, "UNIT", true);
        }
        private void SetField()
        {
            if (selectedReturnImportOrder == null||selectedReturnImportOrder.OrderCode=="")
            {
                return;
            }
            BindDataGrid();
            txtOrderCode.Text = selectedReturnImportOrder.OrderCode;
            SalesReturnOrderEntity ReturnEntity=SalesReturnOrderBs.GetSalesReturnOrderById(selectedReturnImportOrder.ReturnOrderId);
            if (ReturnEntity != null)
            {
                txtReturnCode.Text = ReturnEntity.OrderCode;
                txtReturnCode.Tag = ReturnEntity;
            }
            cmbStatus.SelectedValue = selectedReturnImportOrder.Status;
            txtRemark.Text = selectedReturnImportOrder.Remark;
            UICommon.UICommonFunctions.SetTextBoxPersonName(txtCreatedBy, selectedReturnImportOrder.CreatedBy);
            UICommon.UICommonFunctions.SetTextBoxPersonName(txtModifiedBy, selectedReturnImportOrder.ModifiedBy);
            UICommon.UICommonFunctions.SetTextBoxPersonName(txtApprovedBy, selectedReturnImportOrder.ApprovedBy);
            UICommon.UICommonFunctions.SetTextBoxDate(txtCreatedDate, selectedReturnImportOrder.Created, "yyyy-MM-dd hh:mm:ss");
            UICommon.UICommonFunctions.SetTextBoxDate(txtModifiedDate, selectedReturnImportOrder.Modified, "yyyy-MM-dd hh:mm:ss");
            UICommon.UICommonFunctions.SetTextBoxDate(txtApprovedDate, selectedReturnImportOrder.Approved, "yyyy-MM-dd hh:mm:ss");
        }
        private void BindDataGrid()
        {
            if (selectedReturnImportOrder == null)
            {
                return;
            }
            DataTable dt = InvReturnImportItemBs.GetInvReturnImportItemByOrderId(selectedReturnImportOrder.Id);
            gvMain.DataSource = dt;
        }
        private void BindDetailByreturnItems()
        {

            if (mReturnItems == null)
            {
                return;
            }
            cmbStatus.SelectedValue = "IRIO01";
            DataTable dt = new DataTable();
            dt.Columns.Add("ID");
            dt.Columns.Add("INV_RETURN_IMPORT_ORDER_ID");
            dt.Columns.Add("SALES_RETURN_ITEM_ID");
            dt.Columns.Add("PRODUCT_ID");
            dt.Columns.Add("IMPORT_QTY");
            dt.Columns.Add("MST_WAREHOUSE_ID");
            dt.Columns.Add("MST_LOCATION_ID");

            dt.Columns.Add("PRODUCT_CODE");
            dt.Columns.Add("PRODUCT_NAME");
            dt.Columns.Add("PRODUCT_SPEC_OUT");
            dt.Columns.Add("UNIT");
            dt.Columns.Add("LOCATION_CODE");
            dt.Columns.Add("WAREHOUSE_NAME");

            foreach (SalesReturnItemEntity entity in mReturnItems)
            {
                DataRow dr = dt.NewRow();
                dr["ID"] = Guid.NewGuid().ToString();
                dr["INV_RETURN_IMPORT_ORDER_ID"] = selectedReturnImportOrder.Id;
                dr["SALES_RETURN_ITEM_ID"] = entity.Id;
                dr["PRODUCT_ID"] = entity.ProductId;
                MstProductEntity Product=MstProductBs.GetProductByProductId(entity.ProductId);
                if (Product != null)
                {
                    dr["PRODUCT_CODE"] = Product.ProductCode;
                    dr["PRODUCT_NAME"] = Product.ProductName;
                    dr["PRODUCT_SPEC_OUT"] = Product.ProductSpecOut;
                    dr["UNIT"] = Product.Unit;
                }
                decimal remindQty = InvReturnImportItemBs.GetRemindQtyBySalesReturnItemId(entity.Id);
                dr["IMPORT_QTY"] = remindQty;
                dt.Rows.Add(dr);
            }

            gvMain.DataSource = dt;

        }
        private void SetEntity()
        {
            if (selectedReturnImportOrder == null)
            {
                selectedReturnImportOrder = new InvReturnImportOrderEntity();
                selectedReturnImportOrder.Id = Guid.NewGuid().ToString();
            }
            if(txtReturnCode.Tag!=null &&txtReturnCode.Tag.GetType()==typeof(SalesReturnOrderEntity))
            {
                selectedReturnImportOrder.ReturnOrderId = ((SalesReturnOrderEntity)txtReturnCode.Tag).Id;

            }
            selectedReturnImportOrder.Remark = txtRemark.Text;

            if (ThisActionType == ActionType.New)
            {
                selectedReturnImportOrder.Status = "IRIO01";
                selectedReturnImportOrder.CreatedBy = CommonParameter.CurrentUser.PersonId;
                selectedReturnImportOrder.Created = DateTime.Now;
                selectedReturnImportOrder.ModifiedBy = CommonParameter.CurrentUser.PersonId;
                selectedReturnImportOrder.Modified = DateTime.Now;
            }
            if (ThisActionType == ActionType.Modify)
            {
                selectedReturnImportOrder.Status = "IRIO02";
                selectedReturnImportOrder.ModifiedBy = CommonParameter.CurrentUser.PersonId;
                selectedReturnImportOrder.Modified = DateTime.Now;
            }
        }
        private bool CheckData()
        {
            if (string.IsNullOrEmpty(txtOrderCode.Text))
            {
                MessageBox.Show("退货单号不能为空", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            DataTable dt = gvMain.DataSource as DataTable;
            if (mReturnItems == null||mReturnItems.Count==0)
            {
                foreach (DataRow dr in dt.Rows)
                {
                    if (dr["LOCATION_CODE"].ToString() == "" || dr["MST_LOCATION_ID"].ToString() == "")
                    {
                        MessageBox.Show("库位不能为空", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return false;
                    }
                    if (dr["WAREHOUSE_NAME"].ToString() == "" || dr["MST_WAREHOUSE_ID"].ToString() == "")
                    {
                        MessageBox.Show("仓库不能为空", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return false;
                    }
                    if (dr["PRODUCT_ID"].ToString()=="")
                    {
                        MessageBox.Show("物品编码不能为空", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return false;
                    }
                    
                }
            }
            return true;
        }
        private bool Save()
        {
            try
            {
                if (CheckData() == false)
                {
                    return false;
                }

                if (ThisActionType == ActionType.New)
                {
                    SetEntity();
                    DataTable dt = gvMain.DataSource as DataTable;
                    string msg = "";
                    bool isSuccessful = InvReturnImportOrderBs.CreateReturnImportOrder(selectedReturnImportOrder, dt, true, msg);
                    if (!isSuccessful)
                    {
                        MessageBox.Show("新增失败！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return false;
                    }
                }
                else if (ThisActionType == ActionType.Modify)
                {
                    SetEntity();
                    DataTable dt = gvMain.DataSource as DataTable;
                    string msg = "";
                    bool isSuccessful = InvReturnImportOrderBs.CreateReturnImportOrder(selectedReturnImportOrder, dt, false, msg);
                    if (!isSuccessful)
                    {
                        MessageBox.Show("修改失败！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return false;
                    }
                }
                else if (ThisActionType == ActionType.Approve)
                {
                    SetEntity();
                    selectedReturnImportOrder.Approved = DateTime.Now;
                    selectedReturnImportOrder.ApprovedBy = CommonParameter.CurrentUser.PersonId;
                    DataTable dt = gvMain.DataSource as DataTable;
                    string msg="";
                    bool isSuccessful = InvReturnImportOrderBs.ApproveReturnImportOrder(selectedReturnImportOrder, dt,msg);
                    if (!isSuccessful)
                    {
                        MessageBox.Show("审核失败！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return false;
                    }
                } 
                return true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
        }

        #endregion

        private void frmMaintainReturnImportOrder_Load(object sender, EventArgs e)
        {
            BindComboBox();
            SetField();
            BindDetailByreturnItems();
        }
        protected override void Click_Save()
        {
            if (Save())
            {
                this.DialogResult = DialogResult.OK;
            }
        }
        protected override void Click_Approve()
        {
            if (selectedReturnImportOrder == null)
            {
                return;
            }
            selectedReturnImportOrder.Status = "IRIO03";
            if (Save())
            {
                this.DialogResult = DialogResult.OK;
            }
        }
        protected override void Click_Reject()
        {
            if (selectedReturnImportOrder == null)
            {
                return;
            }
            selectedReturnImportOrder.Status = "IRIO04";
            if (Save())
            {
                this.DialogResult = DialogResult.OK;
            }
        }

        private void colProductCode_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            
        }

        private void colLocation_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            if (mSelectedRow == null)
            {
                return;
            }
            frmMaintainLocationQuery frm = new frmMaintainLocationQuery();
            if (frm.ShowDialog() == DialogResult.OK)
            {
                mSelectedRow["LOCATION_CODE"] = frm.SelectLocation.LocationCode;
                mSelectedRow["MST_LOCATION_ID"] = frm.SelectLocation.LocationId;
                mSelectedRow["MST_WAREHOUSE_ID"] = frm.SelectLocation.WarehouseCode;
                MstWarehouseEntity entity = MstWarehouseBs.GetMstWarehouseByID(frm.SelectLocation.WarehouseCode);
                if (entity != null)
                {
                    mSelectedRow["WAREHOUSE_NAME"] = entity.WarehouseName;
                }
            }
            else
            {
                mSelectedRow["LOCATION_CODE"] = "";
                mSelectedRow["MST_LOCATION_ID"] = "";
                mSelectedRow["MST_WAREHOUSE_ID"] = "";
                mSelectedRow["WAREHOUSE_NAME"] = "";
            }
        }

        private void colWareHouse_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            if (mSelectedRow == null)
            {
                return;
            }
            frmMaintainWareHouseQuery frm = new frmMaintainWareHouseQuery();
            if (frm.ShowDialog() == DialogResult.OK)
            {
                mSelectedRow["MST_WAREHOUSE_ID"] = frm.SelectedWarehouse.WarehouseCode;
                mSelectedRow["WAREHOUSE_NAME"] = frm.SelectedWarehouse.WarehouseName;
            }
            else
            {
                mSelectedRow["MST_WAREHOUSE_ID"] = "";
                mSelectedRow["WAREHOUSE_NAME"] = "";
            }
        }

        //private void gridView1_RowClick(object sender, DevExpress.XtraGrid.Views.Grid.RowClickEventArgs e)
        //{
        //    mSelectedRow = gridView1.GetDataRow(e.RowHandle);
        //}

        private void gridView1_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            mSelectedRow = gridView1.GetDataRow(e.FocusedRowHandle);
        }
    }
}